<template>
  <el-table class="colorful-table" :data="tableData" style="width: 100%">
    <el-table-column
      v-for="item in column"
      :key="item.prop"
      :prop="item.prop"
      :label="item.label"
      :width="item.width|| 'auto'"
      :min-width="item.minWidth|| 104"
      header-align="center"
      :show-overflow-tooltip="item.showTooltip"
    >
      <template #default="{ row }">
        <div
          class="colorful-table__cell"
          :class="[{'base-text-ellipsis':item.showTooltip},colorFormat(row[item.prop],item.type)]"
        >
          <slot :name="item.prop">
            {{ dataFormat(row[item.prop],item.type,item.format) }}
          </slot>
        </div>
      </template>
    </el-table-column>
  </el-table>
</template>

<script setup lang='ts'>
import dayjs from 'dayjs';
import { type PropType } from 'vue';
import { formatPercentUnit } from '@/utils';
defineOptions({
  name: 'ColorfulTable'
});
defineProps({
  tableData: {
    type: Array,
    default: () => {
      return [];
    }
  },
  column: {
    type: Array as PropType<any[]>,
    default: () => {
      return [];
    }
  }
});
const colorFormat = (val: number | string, type: string) => {
  if (type === 'time' || type === 'normal' || typeof val !== 'number') {
    return '';
  }
  if (!val) {
    return '';
  } else if (val <= 0.2) {
    return 'color-0-20';
  } else if (val <= 0.4) {
    return 'color-20-40';
  } else if (val <= 0.6) {
    return 'color-40-60';
  } else if (val <= 0.8) {
    return 'color-60-80';
  } else {
    return 'color-80-100';
  }
};
const dataFormat = (value: number | string, type: string, format = 'YYYY-MM-DD HH:mm:ss') => {
  if (typeof value !== 'number' || type === 'normal') { // 非数字和不需要处理的字段
    if (!value) {
      return '-';
    }
    return value;
  }
  if (!value) return 0;
  if (type === 'time') return dayjs.unix(value).format(format);// 日期字段
  return formatPercentUnit(value);
};
</script>

<style lang="scss" scoped>
.colorful-table {
  &__cell {
    min-width: 50px;
    padding: 12px 16px 13px;
    line-height: 23px;
    color: #303133;
    text-align: center;

    &.color-0-20 {
      background-color: #EBEEF5;
    }

    &.color-20-40 {
      background-color: #DBE3FB;
    }

    &.color-40-60 {
      background-color: #B6C8F6;
    }

    &.color-60-80 {
      background-color: #92ACF2;
    }

    &.color-80-100 {
      background-color: #6D91ED;
    }
  }

  :deep(.el-table) {
    th.el-table {
      &__cell {
        min-width: 50px;
        padding: 12px 16px 13px;
        font-style: normal;
        font-weight: 600;
        line-height: 22px;
        color: #909399;
        background-color: #F5F7FA;
      }
    }

    .cell {
      padding: 0;
      line-height: initial;
    }

    .el-table {
      &__cell {
        padding: 0;
      }

    }
  }
}
</style>
